package io.renren.common.utils;

import io.renren.common.vo.GroupItemVo;
import io.renren.common.vo.output.NextWordVo;
import io.renren.config.BizConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: xiaomi
 * @date: 2022/2/7
 * @description: 业务上的工具方法
 */
public class BizUtils {

    /**
     * 由于WX 组件不支持带请求头的方式！所以只能用请求参数：key-value 的方式了！
     */
    private static Map<String, String> defaultCOSMap = new HashMap<>();

    /**
     * 请求参数
     */
    private static Map<String, String> defaultCOSParamsMap = new HashMap<>();

    /**
     * 微信小程序资源的请求头
     */
    public static final String WX_RESOURCE_PARAM = "&cos=daimaoking";

    static {
        //NOTEME 需要按照标准请求头的方式
        defaultCOSMap.put("x-cos-meta-cos", "daimaoking");
        defaultCOSParamsMap.put("cos", "daimaoking");
    }

    //region 通用业务

    /**
     * 默认第一页，10个
     *
     * @return
     */
    public static Map<String, Object> getDefaultPageParam() {
        Map<String, Object> map = new HashMap<>(6);
        map.put("page", "1");
        map.put("limit", "10");
        return map;
    }

    public static Map<String, Object> getPageParam(int pageIndex, int limit) {
        Map<String, Object> map = new HashMap<>(6);
        map.put("page", pageIndex + "");
        map.put("limit", limit + "");
        return map;
    }

    /**
     * 通过 20220101 格式生成对应的 LocalDate
     *
     * @param studyDate
     * @param year
     * @return
     */
    public static LocalDate genLocalDateByIntDate(Integer studyDate, int year) {
        int left = studyDate - year * 10000;
        int month = left / 100;
        int dayOfMonth = left - month * 100;
        LocalDate localDate = LocalDate.of(year, month, dayOfMonth);
        return localDate;
    }

    /**
     * 根据文件流生成对应文本
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static String getContentFromMultipartFile(MultipartFile multipartFile) throws IOException {
        Reader reader = null;
        reader = new InputStreamReader(multipartFile.getInputStream(), "utf-8");
        BufferedReader br = new BufferedReader(reader);
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
            // 一次读入一行数据
//            if(line!=null && line!=""){
//                sb.append(line);
//            }
        }
        reader.close();
        return sb.toString();
    }

    public static String getContentFrom(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        //List<String> strings = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);
        byte[] bytes = new byte[0];
        bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        String str = new String(bytes);
        return str;
    }
    //endregion

    //region 单词业务

    /**
     * 生成首字母大写的单词
     *
     * @param word
     * @return
     */
    public static String genFirstLetterUpperWord(String word) {
        if (StringUtils.isBlank(word)) {
            return "";
        }
        String res = (word.toCharArray()[0] + "").toUpperCase().concat(word.substring(1));
        return res;
    }

    /**
     * 分割解释
     * eg.1.n. 磨坊主；碾磨工；蛾 2.n. (Miller)人名；(西、葡)米列尔；(英、德、法、爱沙、芬、罗、瑞典、波)米勒 
     * 按照1. 2. 这种进行分割
     *
     * @param vo
     * @param explanation
     */
    public static void genNextWordVoExplanationListByExplanation(NextWordVo vo, String explanation) {
        if (StringUtils.isBlank(explanation)) {
            vo.setExplanations(new ArrayList<>());
            return;
        }
        List<String> ll = new ArrayList<>();
        String[] strings = explanation.split(BizConfig.REGEX_EXPLANATION_SPLIT);
        for (String string : strings) {
            String temp = string.trim();
            if (StringUtils.isNotBlank(temp)) {
                ll.add(temp);
            }
        }
        vo.setExplanations(ll);
    }

    /**
     * 生成给前端的路径
     *
     * @param vo
     * @param pronunciationRelativePath
     */
    public static void genNextWordVoPronunciationPathByLocal(NextWordVo vo, String pronunciationRelativePath) {
        if (StringUtils.isNotBlank(pronunciationRelativePath)) {
            vo.setPronunciationPath(BizConfig.PATH_PRE.concat("/").concat(pronunciationRelativePath.trim().replace("\\", "/")));
        }
    }

    public static void genNextWordVoPronunciationPathByLocal(NextWordVo vo, String pronunciationRelativePath, String pathPre) {
        if (StringUtils.isNotBlank(pronunciationRelativePath)) {
            vo.setPronunciationPath(pathPre.concat(BizConfig.PATH_RESOURCE_RELATIVE_PRE).concat("/").concat(pronunciationRelativePath.trim().replace("\\", "/")));
        }
    }


    //endregion

    //region 笔记业务

    public static String genDetail(String keyword, String regex, String content, int count, String addStr, String nextLineStr, boolean ifHighLight) {
        StringBuilder sb = new StringBuilder();
        String[] strings = content.split(regex);
        int lenLimit = strings.length - 1;
        for (int i = 0; i < lenLimit; i++) {
            String pre = getPostStrByCount(strings[i], count, addStr);
            String post = getPreStrByCount(strings[i + 1], count, addStr);
            if (ifHighLight) {
                sb.append(pre).append("<span class=\"hl\" style=\"color: red;\">").append(keyword).append("</span>").append(post).append(nextLineStr);
            } else {
                sb.append(pre).append(keyword).append(post).append(nextLineStr);
            }

        }
        return sb.toString();
    }

    /**
     * 获取字符串的前几个字
     *
     * @param str
     */
    private static String getPreStrByCount(String str, int count, String addStr) {
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            //获取前面三个
            if (str.length() > count) {
                return str.substring(0, count).concat(addStr);
            } else {
                return str;
            }
        }
    }

    private static String getPostStrByCount(String str, int count, String addStr) {
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            //获取后面三个
            if (str.length() > count) {
                return addStr.concat(addStr).concat(str.substring(str.length() - count));
            } else {
                return str;
            }
        }
    }

    /**
     * 由于mysql 的 like 不区分大小写，所以将 keyword 转为 pattern
     *
     * @param keyword
     * @return
     */
    public static String genRegexFromKey(String keyword) {
        if (StringUtils.isBlank(keyword)) {
            return "";
        }
        //进行转换
        char[] chars = keyword.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char c : chars) {
            //判断 c 是否为一个大写的
            if (Character.isUpperCase(c)) {
                //是大写
                sb.append("[").append(Character.toLowerCase(c)).append(c).append("]");
            } else if (Character.isLowerCase(c)) {
                //是小写
                sb.append("[").append(c).append(Character.toUpperCase(c)).append("]");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 通过正则表达式匹配正文详情
     * {@See MatcherT}
     *
     * @param content
     * @param regex
     * @return
     */
    public static String genAllByRegex(String content, String regex) {
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(content);
        StringBuilder sb = new StringBuilder();
        int beginIndex = 0;
        while (matcher.find()) {
            //pre
            sb.append(content.substring(beginIndex, matcher.start()));
            //core
            sb.append("<span class=\"hly\">").append(content.substring(matcher.start(), matcher.end())).append("</span>");
            //post
            beginIndex = matcher.end();
        }
        sb.append(content.substring(beginIndex));
        return sb.toString();
    }

    public static String genDetailByRegex(String content, String regex, int count, String addStr, String nextLineStr) {
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(content);
        int beginIndex = 0, endIndex = 0;
        StringBuilder sb = new StringBuilder();
        int lenLimit = content.length() - 1;
        while (matcher.find()) {
            //pre
            beginIndex = matcher.start() - count;
            beginIndex = beginIndex >= 0 ? beginIndex : 0;
            sb.append(addStr).append(content.substring(beginIndex, matcher.start()));
            //core
            sb.append("<span class=\"hly\" style=\"background-color: yellow;\">").append(content.substring(matcher.start(), matcher.end())).append("</span>");
            //post
            endIndex = matcher.end() + count;
            endIndex = endIndex >= lenLimit ? lenLimit : endIndex;
            sb.append(content.substring(matcher.end(), endIndex)).append(addStr);

            sb.append(nextLineStr);
        }
        return sb.toString();
    }

    /**
     * @param time 08:23
     * @return
     */
    public static long internalTimeStamp(String time) {
        String[] split = time.split(":");
        int hour = Integer.parseInt(split[0]);
        int minutes = Integer.parseInt(split[1]);
        //下一个8.
        //1.获取当天8.
        Date now = new Date();
        //设置东八区
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, 0);
        Date tempDate = calendar.getTime();
        if (now.compareTo(tempDate) < 0) {
            //当前时间小
        } else {
            calendar.add(Calendar.DATE, 1);
            tempDate = calendar.getTime();
        }
        return tempDate.getTime() - now.getTime();
    }

    /**
     * 获取文件格式
     *
     * @param path
     * @return
     */
    public static Integer genFileType(String path) {
        if (path.startsWith("http")) {
            return 5;
        }
        if (path.startsWith("《")) {
            //如果是书名
            return 6;
        }
        //本地路径
        String fileExtension = path.lastIndexOf(".") != -1 && path.lastIndexOf(".") != 0 ? path.substring(path.lastIndexOf(".") + 1).toLowerCase() : null;
        if (fileExtension == null) {
            return 7;
        }

        Integer res = 0;
        switch (fileExtension) {
            case "md":
                res = 1;
                break;
            case "pdf":
                res = 2;
                break;
            case "doc":
                res = 3;
                break;
            case "mp4":
                res = 4;
                break;
        }
        return res;
    }

    /**
     * 根据全路径获取文件名称
     *
     * @param path
     * @return
     */
    public static String getFileNameByPath(String path) {
        int index1 = path.lastIndexOf("/");
        int index2 = path.lastIndexOf("\\");
        if (index1 == -1 && index2 == -1) {
            return path;
        }
        //
        int max = Math.max(index1, index2);
        return path.substring(max + 1);
    }

    public static Map<String, Integer> genDateNumMap(List<GroupItemVo> itemVos) {
        Map<String, Integer> map = new HashMap<>();
        for (GroupItemVo itemVo : itemVos) {
            String str = itemVo.getLabel().toString();
            map.put(str.substring(0, 4).concat("-").concat(str.substring(4, 6)).concat("-").concat(str.substring(6)), itemVo.getNum());
        }
        return map;
    }

    public static Map<String, String> getDefaultStoreHeaders() {
        return defaultCOSMap;
    }

    public static Map<String, String> getDefaultStoreParams() {
        return defaultCOSParamsMap;
    }

    //endregion


}
